//
//  STComposeView.swift
//  STVVeibo
//
//  Created by leergou on 16/7/28.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

/*
    此 view 主要用于加载磨玻璃效果的背景图片 和 带pop 动画效果的按钮
    是点击 mainViewController 中 撰写 按钮,加载 此 view 到 mainViewController 的 view 上
*/

import UIKit
import pop

class STComposeView: UIView {
    
    // 定义一个 target,记录
    var target: UIViewController?
    // 定义一个数组,保存按钮信息,便于给按钮赋值 -> lazy 可加可不加
    lazy var composeButtonInfoList:[STComposeButtonInfo] = [STComposeButtonInfo]()
    // 定义一个数组,保存 composetButton
    lazy var composeButtons:[STComposeButton] = [STComposeButton]()

    override init(frame: CGRect) {
        super.init(frame: UIScreen.mainScreen().bounds)
        backgroundColor = RandomColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 监听方法
    @objc private func composeButtonClick(sender: STComposeButton){
//        print("点击按钮了")
        // 设置动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            // 遍历按钮数组
            for value in self.composeButtons{
                // 设置透明度
                value.alpha = 0.2
                // 判断遍历的按钮是否是当前的按钮
                if value == sender {
                    // 是点击按钮,放大
                    value.transform = CGAffineTransformMakeScale(2, 2)
                } else {
                    // 不是点击按钮,缩小
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 动画结束后,遍历数组,恢复按钮形状
                    for value in self.composeButtons {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                    }
                    
                    }, completion: { (_) -> Void in
                        
                        // 控制器跳转
                        // 1.首先判断从 plist中取出的 类名是否为空
                        guard let vcName = sender.composeButtonInfo?.nextvc else {
                            return
                        }
                        
                        // 自定义类,进行动态生成的话,要在类名前 加上 项目名称,格式为 项目名.类名
                        // 获取 项目名
                        // 2.判断获取的自定义类名是否存在
                        guard let projectName = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else {
                            return
                        }
                        
                        // 判断 class 类名是否为 nil,而且是否可以转成 UIViewController.Type
                        // OC中没有命名空间,而 swift 中有命名空间,所以如果在swift 中获取自定义类class,格式为 [项目名.类名]
                        // 3.判断获取的类是否为空,并且是否可以转成指定的类型
                        guard let clazz = NSClassFromString("\(projectName).\(vcName)") as? UIViewController.Type else {
//                            print("\(projectName).\(vcName)")
                            return
                        }
                        
                        // 初始化类
                        let tempVc = clazz.init()
                        let navC = UINavigationController(rootViewController: tempVc)
                        self.target?.presentViewController(navC, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                })
        }
    }
    
    //MAKR: 加载视图
    func composeViewShow(target: UIViewController){
        target.view.addSubview(self)
        self.target = target
        //按钮 添加动画
        setupButtonAnimation(true)
    }
    
    // 屏幕点击事件 --> 隐藏按钮
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//        removeFromSuperview()
        // 点击屏幕隐藏按钮
        setupButtonAnimation(false)
    }
    

    //MAKR: - setupUI
    func setupUI(){
        //backgroundColor = RandomColor()
        // 添加子控件
        addSubview(bgImageView)
        addSubview(logoImageView)
        addChildButton()
        
        // 约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero);
        }
        logoImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
    }
    
    //MARK: - 设置 buttons 的动画(isUP: true ,代表向上,false,向下)
    func setupButtonAnimation(isUp: Bool){
        
        let margin: CGFloat = isUp ? -350 : 350
        let set = isUp ? composeButtons.enumerate() : composeButtons.reverse().enumerate()
        
        //按钮 添加动画
        for (index, value) in set {
            // 设置动画
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 设置 tovalue
            animation.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
            // 开始时间
            animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025 // CACurrentMediaTime() 系统时间
            // 弹性系数
            animation.springBounciness = 10
            // 动画速度
            animation.springSpeed = 8
            value.pop_addAnimation(animation, forKey: nil)
        }
    }
    
    //MAKR: - 创建并添加按钮
    func addChildButton(){
        // 获取按钮信息
        composeButtonInfoList = getButtonInfo()
        //定义按钮宽和高
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 110
        // 按钮间距
        let margin = (SCREENW - 3 * buttonWidth) / 4
        
        // for 循环 ,添加按钮(九宫格算法)
        for (index, value) in composeButtonInfoList.enumerate(){
            let columns: Int = 3
            let row = CGFloat(index / columns)
            let col = CGFloat(index % columns)
            
            let button = STComposeButton(title: value.title, imageName: value.icon, target: self, action: "composeButtonClick:")
            button.composeButtonInfo = composeButtonInfoList[index]
            
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
            button.frame = CGRect(x: ((col + 1) * margin + col * buttonWidth), y: ((row + 1) * margin + row * buttonHeight) + SCREENH, width: buttonWidth, height: buttonHeight)
            addSubview(button)
            // 添加按钮到数组
            composeButtons.append(button)
        }
    }
    
    //MAKR: 加载按钮信息
    func getButtonInfo() -> [STComposeButtonInfo]{
        // 读取文件路径
        let pathString = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        // 读取文件内容到数组
        let tempArray = NSArray(contentsOfFile: pathString)!
        // 定义一个可变数组
        var mutableArray:[STComposeButtonInfo] = [STComposeButtonInfo]()
        // 遍历临时数组,字典转模型
        for dic in tempArray{
            // 创建模型
            let composeButtonInfo: STComposeButtonInfo = STComposeButtonInfo(dict: dic as! [String : AnyObject])
            // 添加到可变数组
            mutableArray.append(composeButtonInfo)
        }
        return mutableArray
    }
    
    
    
    //MAKR: lazy
    private lazy var logoImageView: UIImageView = UIImageView(imgName: "compose_slogan")
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
}














